<?php

namespace App\Http\Controllers\Api;

use App\Models\MemberRecommend;
use App\Repositories\Api\MemberRepository;
use App\Repositories\WechatRepository;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LoginController extends MiniAppController
{
    private $memberRep = null;

    public function __construct(MemberRepository $memberRep)
    {
        parent::__construct();
        $this->memberRep = $memberRep;
    }

    public function index(Request $request)
    {
        //接收参数
        $code = $request->post('code');
        if (!isset($code)) {
            return retFail("code 异常,请稍后再试");
        }

        try {
            $wechatRepository = new WechatRepository();
            $wxSession = $wechatRepository->toSession($code);

            if (isset($wxSession['errcode']))//解析错误
                return retFail($wxSession['errmsg']);

            $member = $this->memberRep->adminLogin($wxSession['unionid'] ?? "", $wxSession['openid']);
            if (empty($member['unionid']) && !empty($member)) {
                $this->memberRep->updateFields($member['id'], ['unionid' => $wxSession['unionid']]);
            }

            if (empty($member['weapp_openid']) && !empty($member)) {
                $this->memberRep->updateFields($member['id'], ['weapp_openid' => $wxSession['openid']]);
            }

            if (empty($member)) {
                $mData['gender'] = 0;
                $mData['weapp_openid'] = $wxSession['openid'];
                $mData['unionid'] = $wxSession['unionid'] ?? "";
                $mData['reg_ip'] = request()->ip();

                $res = $this->memberRep->saveOrUpdate($mData);
                $member = $this->memberRep->adminLogin($wxSession['unionid'] ?? "", $wxSession['openid']);

                if (!empty($member)) { //推荐
                    $share_id = request()->input("share_id"); //分享会员编号
                    $uid = 0;

                    if ($share_id && $share_id != $uid) {//增加推荐 -> 系统
                        MemberRecommend::insert([
                            'ruid' => $share_id,
                            'uid' => $member['id'],
                            'from' => "weapp",
                            'create_time' => date("Y-m-d H:i:s")
                        ]);
//                        $this->memberRep->award_mini_share($member['id'], 41);
//                        (new  MemberMiniRecommendRepository())->statExceptionRecommend($share_id);
                    }
                }
            }
            /*
             *  is_new  2: 后台 1： 走前台
             */
            setRedisByDb("session_key_" . $member['id'], $wxSession['session_key']);
            return $this->apiResponse->success($member);
        } catch (Exception | GuzzleException $e) {
            $errorMessage = $e->getMessage();

            Log::error(
                'decode error',
                [
                    'messages' => $errorMessage . '::' . json_encode(Request()->all()),
                    'code' => $e->getCode(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ]
            );

            if ($errorMessage == 'The given payload is invalid.') {
                return retFail('解码失败，请重试' . $errorMessage);
            }
            return retFail('执行失败:' . $errorMessage);
        }
    }

    /**
     * Api 图形验证码
     */
    public function captcha()
    {
        return $this->apiResponse->success([
            'url' => app('captcha')->create('default', true)
        ], 'success', 200, []);
    }

}
